import { Button, Calendar, DatePicker, Divider, Dropdown, Input, InputNumber, List, message, Popconfirm, Space, Tag, type CalendarProps } from "antd";
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import type { DatePickerProps, MenuProps } from 'antd';
import { useEffect, useState } from "react";
import { HolidayUtil, Lunar } from 'lunar-typescript';
import style from './index.module.css'
import classNames from 'classnames'
import { useMediaQuery } from 'react-responsive'
import { DeleteTask, editStatus, editTask, listTask, saveTask } from "@/api/task";
import { DatePicker as MobileDatePicker, Toast } from 'antd-mobile';
import { date } from "@/components/CustomIconSelector/CustomIcons";
import { globalMessage } from "@/utils/message";

interface MyComponent {
    list: any,
    startTime: string,
    handleCancle: () => void;
}
interface queryParams {
    taskId?: string | null,
    title: string | null,
    description: string | null,
    currentOrder:number| 0,
    startTime: string | null,
    endTime: string | null,
    userId: string | null,
}
const TaskListView: React.FC<MyComponent> = (props) => {
    const isMobile = useMediaQuery({ maxWidth: 768 })
    const [isCreateMobileDateOpen, setIsCreateMobileDateOpen] = useState<boolean>(false)
    const [isEndMobileDateOpen, setIsEndMobileDateOpen] = useState<boolean>(false)


    const [taskList, setTaskList] = useState([])
    const [isOpen, setIsOpen] = useState<boolean>(false)
    const query = {
        title: null,
        description: null,
        startTime: null,
        currentOrder: 0,
        endTime: null,
        userId: "2",
    }
    const [queryParams, setQueryParams] = useState<queryParams>(query)

    useEffect(() => {
        setTaskList([...props.list])
        setQueryParams({
            ...queryParams,
            startTime: props.startTime,
            endTime: props.startTime
        })
    }, [props.list, props.startTime])


    const getMenuItems = (item: any): MenuProps['items'] => [
        {
            key: '0',
            label: <Popconfirm
                title="删除"
                description={`是否删除taskId为${item.taskId}的数据`}
                okText="是"
                placement="leftTop"
                onConfirm={() => handleDeleteClick(item)}
                cancelText="否">
                <Button type="link" size="small" >删除</Button>
            </Popconfirm>,
        },
        {
            key: '1',
            label: <Popconfirm
                title="是否修改状态"
                okText="是"
                placement="leftTop"
                onConfirm={() => handleStatusClick(item)}
                cancelText="否">
                <Button type="link" size="small" >状态</Button>
            </Popconfirm>,
        },
        {
            key: '2',
            label: <Button type="link" size="small" onClick={() => handleClick(item)} >修改</Button>,
        },
    ];



    const handleClick = (item: any) => {
        setQueryParams({
            ...item
        })
        setIsOpen(true)
    }
    const handleAdd = () => {
        setQueryParams({ ...query, startTime: props.startTime, endTime: props.startTime })
        setIsOpen(true)
    }
    const handleStatusClick = (item: any) => {
        const completed = item.overStatus ? false : true
        editStatus({ taskId: item.taskId, date:props.startTime,completed }).then((res: any) => {
            if (res.code == 200) {
                 globalMessage().success(`修改成功`)
                props.handleCancle()
            }
        })
    }
    const handleCancle = () => {
        setIsOpen(false)
        props.handleCancle()
    }
    const handleDeleteClick = (item) => {
        const taskIds = [item.taskId]
        DeleteTask(taskIds).then((res: any) => {
            if (res.code == 200) {
                 globalMessage().success(`已删除${res.data}`)
                props.handleCancle()
            }
        })
    }
    const handSave = () => {
        const dayjsTime1 = dayjs(queryParams.startTime, 'YYYY-MM-DD HH:mm:ss');
        const dayjsTime2 = dayjs(queryParams.endTime, 'YYYY-MM-DD HH:mm:ss');
        if (!dayjsTime2.isAfter(dayjsTime1)) {
             globalMessage().warning("结束时间要>开始时间")
            return;
        }
        if (queryParams.title == null || queryParams.description == null) {
             globalMessage().warning("请填写标题和内容")
            return;
        }
        if (!queryParams?.taskId) {
            saveTask(queryParams).then((res: any) => {
                if (res.code == 200) {
                     globalMessage().success("保存成功")
                    handleCancle()
                }
            })
        } else {
            editTask(queryParams).then((res: any) => {
                if (res.code == 200) {
                     globalMessage().success("修改成功")
                    handleCancle()
                }
            })
        }
    }
    const onCreateTimeOk = (value: DatePickerProps['value']) => {
        console.log('onOk: ', value);
    };
    return (
        <div className={"w-full"}>
            {isOpen !== true &&
                <div>
                    <div className={'pl-1 flex justify-between'}>
                        <Button onClick={handleAdd} type="link" size="small" >
                            新增
                        </Button>
                        <Button onClick={props.handleCancle} type="link" size="small" >
                            刷新
                        </Button>
                    </div>

                    <List
                        itemLayout="horizontal"
                        dataSource={taskList}
                        renderItem={(item) =>
                            <div className={"p-2"}>
                            <div className={ 'w-full  p-1 border border-inherit rounded-xl '} >
                                <div className={'flex justify-between items-center pb-2'} >
                                    <div className={' w-5/6 flex'}>
                                        <div> {item.title}</div>
                                        <div className={'pl-2'}>
                                        </div>
                                    </div>
                                    <div className={'w-1/6 text-right pr-3'}>
                                        <Dropdown menu={{ items: getMenuItems(item) }} trigger={['click']}>
                                            <a className={'text-blue-500'} onClick={(e) => e.preventDefault()}>
                                                操作
                                            </a>
                                        </Dropdown>
                                    </div>
                                </div>
                                <div className={'flex justify-between items-center '} >
                                    <div className={'w-5/6'}>{item.description}</div>
                                    <div className={'w-1/6 text-right'}>
                                    <Tag color={item.overStatus  ? "blue":"gold" }>{item.overStatus ? "已完成" : '未完成'}</Tag>
                                    </div>
                                </div>
                            </div>
                            </div>
                        }
                    />
                </div>
            }
            {/* 新增 */}
            {isOpen &&
                <div>
                    <div className={'flex justify-between'}>
                        <Button type="link" onClick={() => handleCancle()}> 返回</Button>
                        <Button type="link" onClick={handSave}> 保存</Button>
                    </div>
                    <Divider plain></Divider>
                    <div className={'m-2'}>
                        <div className={"w-2/4 pb-2"}>
                            {isMobile ? (
                                <div>
                                    <Button
                                        onClick={() => { setIsCreateMobileDateOpen(true) }}>
                                        开始： {queryParams.startTime}
                                    </Button>
                                    <MobileDatePicker visible={isCreateMobileDateOpen}
                                        onClose={() => {
                                            setIsCreateMobileDateOpen(false)
                                        }}
                                        precision='minute'
                                        onConfirm={value => {
                                            setIsCreateMobileDateOpen(false)
                                            setQueryParams({ ...queryParams, startTime: dayjs(value).format('YYYY-MM-DD HH:MM:ss') })
                                        }} /></div>)
                                : (<DatePicker
                                    prefix="开始"
                                    showTime={{ format: 'HH:mm:ss' }}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    defaultValue={dayjs(queryParams.startTime)}
                                    onChange={(value, dateString) => { }}
                                    
                                    onOk={(value) => {
                                        setQueryParams({ ...queryParams, startTime: value.format('YYYY-MM-DD HH:MM:ss') })
                                    }}
                                />)}
                            {/* 结束时间 */}
                            {isMobile ? (
                                <div>
                                    <Button
                                        onClick={() => { setIsEndMobileDateOpen(true) }}>
                                        结束： {queryParams.endTime}
                                    </Button>
                                    <MobileDatePicker visible={isEndMobileDateOpen}
                                        onClose={() => {
                                            setIsEndMobileDateOpen(false)
                                        }}
                                        precision='minute'
                                        onConfirm={value => {
                                            setIsEndMobileDateOpen(false)
                                            setQueryParams({ ...queryParams, endTime: dayjs(value).format('YYYY-MM-DD HH:MM:ss') })
                                        }} /></div>)
                                : (<DatePicker
                                    prefix="结束"
                                    showTime={{ format: 'HH:mm:ss' }}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    defaultValue={dayjs(queryParams.endTime)}
                                    onChange={(value, dateString) => { }}
                                    onOk={(value) => {
                                        setQueryParams({ ...queryParams, endTime: value.format('YYYY-MM-DD HH:MM:ss') })
                                    }}
                                />)}
                        </div>
                        <div className={"w-2/4 pl-1 pb-2"}>
                            <Input placeholder='请输入标题' onChange={(e) => setQueryParams({ ...queryParams, title: e.target.value })} value={queryParams.title}></Input>
                        </div>
                        <div className={"w-2/4 pl-1 pb-2"}>
                            <InputNumber  placeholder='请输入序号' onChange={(e) => setQueryParams({ ...queryParams, currentOrder:e })} value={queryParams.currentOrder}></InputNumber>
                        </div>
                        <div className={"w-11/12 pl-1 pr-1"}>
                            <Input.TextArea placeholder='请输入描述信息' onChange={(e) => setQueryParams({ ...queryParams, description: e.target.value })} value={queryParams.description}></Input.TextArea>
                        </div>
                    </div>

                </div>
            }


        </div>
    )

}
export default TaskListView;